package com.luoluotech.load.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.luoluotech.load.vo.TemplateBus;
import com.luoluotech.load.vo.TemplateOut1688;
import com.luoluotech.load.vo.TitleSpliteVo;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
public class ExcelUtil {

    public static String userName;
    public static String phone;
    public static String address;


    public void readExcel(String fileName) {
        // 1. 当前路径下是否有文件拆分目录，若是没有则创建，文件夹下面若是有文件，则删除
        this.checkPathAndDeleteFile();
        // 2 easyExcel读取excel文件
        String path = TestFileUtil.getPath()+"/"+ fileName;
        // 检查文件path是否存在 不存在报错并结束
        this.checkFileExists(path);
        final TemplateBus[] one = {null};
        // 每100条输出到一个新的文件
        final int[] count = {1};
        final int[] size = {0};



        // 读取excel文件
        EasyExcel.read(path, TemplateBus.class, new PageReadListener<TemplateBus>(dataList -> {
            TemplateBus firstOne = dataList.get(0);
            this.userName = firstOne.getRecipientName();
            this.phone = firstOne.getContactMobile();
            this.address = firstOne.getShippingAddress();


            Map<String, TemplateBus> collect = dataList.stream().filter(p->p.getSkuId()!=null).collect(Collectors.toMap(TemplateBus::getSkuId, v -> v, (k1, k2) -> k1));
            List<TemplateBus> notEmpty = dataList.stream().filter(p -> p.getSkuId() == null).collect(Collectors.toList());
            List<TemplateBus> values = new ArrayList<>(collect.values());
            values.addAll(notEmpty);
            List<TemplateBus> templateBuses = new ArrayList<>(100);
            for (TemplateBus templateBus : values) {

                templateBuses.add(templateBus);
                if(templateBus.getOrderNumber() == null) {
                    transform(templateBus, one[0]);
                }else {
                    one[0] = templateBus;
                }
                System.out.println(templateBus);

                if(count[0] % 100 == 0) {
                    size[0]++;
                    // 输出到一个新的文件
                    String newPath = TestFileUtil.getPath()+"/temp/"+fileName+"_"+ size[0] +".xls";
                    // 将内容转成要输出的Vo
                    List<TemplateOut1688> outlist = transformToOut1688(templateBuses);
                    // 输出到文件
                    EasyExcel.write(newPath, TemplateOut1688.class).sheet("数据导入页").doWrite(outlist);
                    // 清空list
                    templateBuses.clear();
                }
                count[0]++;

            }
        },Integer.MAX_VALUE)).sheet(0).doRead();

    }

    private List<TemplateOut1688> transformToOut1688(List<TemplateBus> templateBuses) {
        List<TemplateOut1688> outlist = new ArrayList<>(templateBuses.size());
        for (TemplateBus templateBus : templateBuses) {
            TemplateOut1688 out = new TemplateOut1688();
            out.setOrderNumber(templateBus.getOrderNumber());

            // 拆分标题：边缘加厚硅胶揉面垫食品级硅胶垫案板烘焙和面垫面板家用擀面垫子 规格: 通透白【定制款】 颜色: 尺寸：50-70（≈530g）
            // 标题为：边缘加厚硅胶揉面垫食品级硅胶垫案板烘焙和面垫面板家用擀面垫子
            // 产品规格1 规格: 通透白【定制款】
            // 产品规格2 颜色: 尺寸：50-70（≈530g）
            TitleSpliteVo titleSpliteVo = this.getTitleSplite(templateBus.getProductTitle());

            out.setProductName(titleSpliteVo.getTitle());
            out.setQuantity(templateBus.getQuantity());
            out.setProductSpec1(titleSpliteVo.getV1());
            out.setProductSpec2(titleSpliteVo.getV2());
            out.setRecipientName(userName);
            out.setRecipientMobile(phone);
//            out.setRecipientProvince(address);
//            out.setRecipientCity();
//            out.setRecipientDistrict();
//            out.setRecipientAddress();
            out.setMergedAddress(address);
//            out.setBuyerMessage();
            out.setAlibabaProductLinkOrId(String.format("https://detail.1688.com/offer/%s.html", templateBus.getOfferId()));
            out.setDistributionOrSpot(0);
            
            outlist.add(out);
        }
        return outlist;

    }

    private TitleSpliteVo getTitleSplite(String text) {

        TitleSpliteVo titleSpliteVo = new TitleSpliteVo();


        String regex = "(.+?)(\\S+:\\s.*?)(\\S+:\\s.*)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(text);

        if (!matcher.find()) {
            regex = "(.+?)(\\S+:\\s.*)";
            pattern = Pattern.compile(regex);
            matcher = pattern.matcher(text);


            if (!matcher.find()) {
                titleSpliteVo.setTitle(text);
            } else {
                titleSpliteVo.setTitle(matcher.group(1)); ;
                titleSpliteVo.setV1(matcher.group(2));

            }
        } else {
            titleSpliteVo.setTitle(matcher.group(1)); ;
            titleSpliteVo.setV1(matcher.group(2));
            titleSpliteVo.setV2(matcher.group(3));
        }
        return titleSpliteVo;
    }

    private void transform(TemplateBus templateBus, TemplateBus one) {
        if(one == null) {
            return;
        }
        templateBus.setOrderNumber(one.getOrderNumber());
        templateBus.setRecipientName(one.getRecipientName());
        templateBus.setShippingAddress(one.getShippingAddress());
        templateBus.setContactNumber(one.getContactNumber());
        templateBus.setContactMobile(one.getContactMobile());

    }

    private void checkFileExists(String path) {

        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在：" + path);
        }
    }

    private void checkPathAndDeleteFile() {

        // 1. 路径是否存在，不存在则创建
        File file = new File(TestFileUtil.getPath()+"/temp");
        if (!file.exists()) {
            file.mkdirs();
        }


        // 2. 路径下是否有文件，有则删除
        File[] files = file.listFiles();
        if (files!= null && files.length > 0) {
            for (File f : files) {
                f.delete();
            }
        }
    }

    public void execute() {
        // 打印：



    }
}
